import Taro, { Component, useState, useEffect } from '@tarojs/taro';
import { View, Input, Button } from '@tarojs/components';
import { set as setGlobalData, get as getGlobalData } from '../../../utils/globalData';

import './index.scss';
import { env } from '../../../utils/config';
import { getSessionKey, decryptData, register, bindMobile, loginLog, getMemberPic, update } from '../../../services/user';
import { getUserCardCount } from '../../../services/electronicCard';
import { timeFormat, fullImgUrl } from '../../../utils/utils';
import NavigationBar from '../../../components/navigationBar/index';


function Login() {
  const [code, setCode] = useState(null);
  const [isLogin, setIsLogin] = useState(false);
  const navigationBarHeight = Taro.getStorageSync('navigationBarHeight');

  useEffect(() => {
    login()
  }, [])

  function login() {
    Taro.showLoading({
      mask: true
    })
    Taro.setStorageSync('isFirstCome', false)
    Taro.login({
      success: function (res) {
        let data = {
          request_param: '',
          request_body: res,
          err_msg: ''
        }
        var jsonstr = JSON.stringify(data)
        loginLog(jsonstr).then((keyRes) => {

        })
        if (res.code) {
          Taro.hideLoading()
          setCode(res.code)
        }
      },
      fail(err) {
        let data = {
          request_param: '',
          request_body: '',
          err_msg: err
        }
        var jsonstr = JSON.stringify(data)
        loginLog({ jsonstr }).then((keyRes) => {

        })
        Taro.showToast({
          title: '登录异常，请刷新或重新进入',
          icon: 'none'
        });
      }
    })
  }

  function getUserInfo(e) {
    console.log(e)
    if (e.detail.errMsg === 'getUserInfo:ok') {
      Taro.showLoading({
        mask: true
      });
      // 获取session-key

      try {
        Taro.login({
          success: function (res) {
            getSessionKey({ code: res.code }).then((keyRes) => {
              // 解密
              let data = {
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv,
                key: keyRes.key
              };
              decryptData(data).then((decryptRes) => {
                Taro.setStorageSync('openId', decryptRes.openId);
                let unionId = '';
                if (decryptRes.unionId) {
                  unionId = decryptRes.unionId;
                }
                // 用户登录
                let data = {
                  type: 1,
                  nickname: e.detail.userInfo.nickName,
                  openid: decryptRes.openId,
                  avatar: e.detail.userInfo.avatarUrl,
                  unionid: unionId
                };
                getUserProfile();
                register(data).then((res) => {
                  Taro.setStorageSync('isGetScopeUserInfo', 'true');
                  setGlobalData('token', res.token);
                  Taro.setStorageSync('token', res.token);
                  res.user.avatar = fullImgUrl(res.user.avatar);
                  res.user.create_time = timeFormat(res.user.create_time, 'yyyy年MM月dd日');
                  const { user, user_oauth: oauth } = res;
                  user.user_oauth = oauth;
                  Taro.setStorageSync('userInfo', user);
                  setGlobalData('userInfo', user);
                  setGlobalData('initData', true);
                  Taro.hideLoading();
                  Taro.setStorageSync('initData', true);
                  getMemberPic().then(res => {
                    Taro.setStorageSync('MemberPic', res);
                    setGlobalData('MemberPic', res);
                  });
                  getUserCardCount().then((res) => {
                    // 设置电子卡券数量，以判断是否展示 红点
                    Taro.setStorageSync('card_count', res.total);
                    Taro.setStorageSync('will_expire_card_count', res.will_expire);
                  });
                  if (user.mobile) {
                    if (!Taro.getStorageSync('card_no_home')) {
                      if (!Taro.getStorageSync('agent_id')) {
                        if (!Taro.getStorageSync('coupon_no')) {
                          Taro.navigateBack();
                        } else {
                          Taro.redirectTo({
                            url: "/subPackageWork/pages/coupon-exchange/index"
                          })
                        }
                      } else {
                        Taro.redirectTo({
                          url: "/subPackageWork/pages/agent_customizes/index"
                        })
                      }
                    } else {
                      Taro.redirectTo({
                        url: "/subPacKagebWork/pages/bangdingcard/index"
                      })
                    }
                  } else {
                    setIsLogin(true);
                  }
                });
              });
            });
          },
        });
      } catch (error) {
        console.log(error);
        Taro.hideLoading();
      }
    } else {
      Taro.showToast({
        title: '授权登录失败',
        icon: 'none'
      });
    }
  }
  function colseInfo() {
    Taro.redirectTo({
      url: '/pages/user/index',
    });
  }
  function getPhoneNumber(e) {
    if (e.target.errMsg === 'getPhoneNumber:ok') {
      let data = {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        key: Taro.getStorageSync('openId')
      };
      bindMobile(data).then((res) => {
        Taro.showToast({
          title: '绑定成功',
          icon: 'none'
        });
        Taro.navigateBack();
      });
    } else {
      Taro.showToast({
        title: '手机号授权失败',
        icon: 'none'
      });
    }
  }

  function getUserProfile() {
    const userInfo = Taro.getStorageSync('userInfo');
    if (!userInfo) {
      Taro.showToast({
        title: '用户还未登录，请先登录',
        icon: 'none'
      })
    }
    let id = userInfo.id;
    let data = {
      id: id
    }
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        data.nickname = res.userInfo.nickName;
        data.avatar = res.userInfo.avatarUrl
        update(data).then((res) => {
          Taro.setStorageSync('userInfo', res.user);
          setGlobalData('userInfo', res.user);

          Taro.showToast({
            title: '更新成功',
            icon: 'none'
          })
        })
      }
    })
  }

  return (
    <View className='login-item' style={`margin-top: ${navigationBarHeight}`}>
      <NavigationBar text="登录" />
      {
        !isLogin && <View>
          <Button className="btn-getuserinfo" openType="getUserInfo" onGetUserInfo={getUserInfo}>一键授权</Button>
          <Button className="btn-closeinfo" onClick={colseInfo}>暂不授权</Button>

          <View className="tip">小程序授权规则改变，需要您主动授权</View>
        </View>
      }
      {
        isLogin && <View>
          <Button className="btn-getuserinfo" openType="getPhoneNumber" onGetPhoneNumber={getPhoneNumber}>手机号授权</Button>
          <Button className="btn-getUserProfile" onClick={getUserProfile}>授权头像</Button>
          <View className="tip">点击绑定手机号</View>
        </View>
      }
    </View>
  )
}

Login.config = {
  navigationBarTitleText: '登录',
}

export default Login;
